/*
 * @Author: MrDotYan 2564217790@qq.com
 * @Date: 2024-09-14 10:17:05
 * @LastEditors: MrDotYan 2564217790@qq.com
 * @LastEditTime: 2024-09-18 18:22:07
 * @FilePath: /webServer/src/controller/email/email.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
  Body,
  Controller,
  Del,
  Get,
  Inject,
  Post,
  Put,
  Query,
} from '@midwayjs/core';
import { EmailService } from '../../service/email/email.service';
import { Validate } from '@midwayjs/validate';
import { ListParamsValidator, StrIdValidator } from '../../validator';
import {
  EditEmailValidator,
  SaveEmailValidator,
  SendCaptchaValidator,
} from '../../validator/email/email';
import { MailerService } from '@midwayjs/mailer';
import { CaptchaService } from '@midwayjs/captcha';
import { BadRequestError } from '@midwayjs/core/dist/error/http';
import { Context } from '@midwayjs/koa';
import { EmailSchema } from '../../schema';

@Controller('/email', { tagName: '' })
export class EmailController {
  @Inject()
  ctx: Context;

  @Inject()
  emailService: EmailService;

  @Inject()
  mailerService: MailerService;

  @Inject()
  captchaService: CaptchaService;

  @Post('/list', { summary: '列表' })
  @Validate()
  async list(@Body() body: ListParamsValidator<EmailSchema>) {
    const data = await this.emailService.list(body);
    return Object.assign(data, body);
  }

  @Post('/save', { summary: '发送邮件' })
  @Validate()
  async save(@Body() body: SaveEmailValidator) {
    const data = {
      to: body.receiver,
      subject: body.subject,
      text: body.subject,
      html: body.context,
    };
    try {
      const message = await this.mailerService.send(data);
      return await this.emailService.save(
        Object.assign(body, { returnReceipt: message })
      );
    } catch (err) {
      this.ctx.logger.error(err);
      throw new BadRequestError('邮件发送失败！请重试');
    }
  }

  @Get('/info', { summary: '信息' })
  @Validate()
  async info(@Query() body: StrIdValidator) {
    return await this.emailService.info(body.id);
  }

  @Del('/remove', { summary: '删除' })
  @Validate()
  async remove(@Query() body: StrIdValidator) {
    return await this.emailService.remove(body.id);
  }

  @Del('/delete', { summary: '（真）删除' })
  @Validate()
  async realRemove(@Query() body: StrIdValidator) {
    return await this.emailService.realRemove(body.id);
  }

  @Put('/edit', { summary: '编辑' })
  @Validate()
  async edit(@Query() query: StrIdValidator, @Body() body: EditEmailValidator) {
    const email = await this.emailService.info(query.id);
    Object.assign(email, body);
    return await this.emailService.save(email);
  }

  @Post('/sendCaptcha', { summary: '发送验证码邮件' })
  @Validate()
  async send(@Body() body: SendCaptchaValidator) {
    const { id, text: code } = await this.captchaService.text({
      type: 'number',
    });

    const context = `<div
                        style="font-size: 24px;
                                font-weight: bold;
                                text-align:center;
                                display: flex;
                                flex-direction: column;
                                align-items: center;
                                justify-content: center;
                                width: 100%;
                                padding: 80px 10px;
                                border-radius: 16px;
                                background: #f1f1f1;
                      ">
                        <span>${code}</span>
                        <div>5分钟内有效</div>
                        <div>请不要告诉他人哦!</div>
                      </div>
`;

    const data = {
      to: body.email,
      subject: '验证码',
      text: '',
      html: context,
    };
    try {
      const message = await this.mailerService.send(data);

      await this.emailService.save({
        receiver: body.email,
        title: '验证码邮件',
        subject: '验证码',
        context,
        returnReceipt: {
          codeKey: id,
          ...message,
        },
      });

      return { key: id };
    } catch (error) {
      this.ctx.logger.error(error);
      throw new BadRequestError('邮件发送失败！请重试');
    }
  }
}
